package com.ruoyi.manage.service.impl;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.enums.RoleKeyEnum;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.manage.domain.MOrderDistributeEntity;
import com.ruoyi.manage.domain.Orders;
import com.ruoyi.manage.entity.order.OrderDistributeDto;
import com.ruoyi.manage.entity.order.OrderUnbindDto;
import com.ruoyi.manage.mapper.OrderDistributeMapper;
import com.ruoyi.manage.mapper.OrdersMapper;
import com.ruoyi.manage.service.IOrderDistributeService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class IOrderDistributeServiceImpl extends ServiceImpl<OrderDistributeMapper, MOrderDistributeEntity> implements IOrderDistributeService {

    private final  OrdersMapper ordersMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createOrderDistribute(OrderDistributeDto orderDistribute) {

        MOrderDistributeEntity orderDistributeEntity = this.getOne(new LambdaQueryWrapper<MOrderDistributeEntity>().
                eq(MOrderDistributeEntity::getOrderId, orderDistribute.getOrderId()));

        if (ObjectUtil.isNull(orderDistributeEntity)) {
            orderDistributeEntity = new MOrderDistributeEntity();
        }
        if (ObjectUtil.isNotNull(orderDistributeEntity)) {
            switch (Objects.requireNonNull(RoleKeyEnum.getRoleKey(orderDistribute.getRoleKey()))) {
                case MANAGER:
                    Long managerId = orderDistributeEntity.getManagerId();
                    if (ObjectUtil.isNotNull(managerId) && managerId.compareTo(0L) > 0) {
                        throw new ServiceException("当前订单已绑定管理员,请先解除绑定后再操作");
                    }
                    break;
                case WRITER:
                    Long writerId = orderDistributeEntity.getWriterId();
                    if (ObjectUtil.isNotNull(writerId) && writerId.compareTo(0L) > 0) {
                        throw new ServiceException("当前订单已绑定写手,请先解除绑定后再操作");
                    }
                    break;
                default:
            }
        }
        orderDistributeEntity.setOrderId(orderDistribute.getOrderId());
        Long userId = orderDistribute.getUserId();
        switch (Objects.requireNonNull(RoleKeyEnum.getRoleKey(orderDistribute.getRoleKey()))) {
            case MANAGER:
                orderDistributeEntity.setManagerId(userId);
                break;
            case WRITER:
                orderDistributeEntity.setWriterId(userId);
                break;
            default:
        }

        orderDistributeEntity.setWhetherWriter(ObjectUtil.isNotNull(orderDistributeEntity.getWriterId()));

        this.saveOrUpdate(orderDistributeEntity);
        //订单分配给管理员后订单状态变为进行中
        if (CharSequenceUtil.equals(orderDistribute.getRoleKey(), RoleKeyEnum.MANAGER.getCode())) {
            this.updateOrderStatus(orderDistribute.getOrderId());
        }
    }

    private void updateOrderStatus(String orderId) {
        List<SysDictData> orderStatusList = DictUtils.getDictCache("order_status");
        assert orderStatusList != null;
        Optional<SysDictData> first = orderStatusList.stream().filter(item -> item.getDictCode().compareTo(101L) == 0).findFirst();
        String orderStatus = first.isPresent() ? first.get().getDictValue() : "2";

        Orders orderUpdateStatus = ordersMapper.selectByOrderId(orderId);
        orderUpdateStatus.setOrderStatus(orderStatus);
        orderUpdateStatus.setUpdateTime(new Date());
        orderUpdateStatus.setUpdateBy(SecurityUtils.getLoginUser().getUsername());
        ordersMapper.updateOrders(orderUpdateStatus);
    }

    @Override
    public void orderUnbind(OrderUnbindDto orderUnbind) {
        Orders orders = ordersMapper.selectByOrderId(orderUnbind.getOrderId());
        if (ObjectUtil.isNull(orders)) {
            throw new ServiceException("订单信息不存在");
        }
        List<SysDictData> orderStatusList = DictUtils.getDictCache("order_status");
        //订单未开始或被退稿，可以解除绑定
        List<SysDictData> dictDataList = orderStatusList.
                stream().
                filter(item -> !(item.getDictCode().compareTo(100L) == 0) && !(item.getDictCode().compareTo(101L) == 0)).
                collect(Collectors.toList());

        List<String> dictValueList = dictDataList.stream().map(SysDictData::getDictValue).collect(Collectors.toList());

        if (dictValueList.contains(orders.getOrderStatus())) {
            throw new ServiceException("当前订单已完成或待修改状态,无法解除绑定");
        }
        String roleKey = orderUnbind.getRoleKey();
        this.lambdaUpdate().
                set(CharSequenceUtil.equals("manager", roleKey), MOrderDistributeEntity::getManagerId, 0).
                set(CharSequenceUtil.equals("writer", roleKey), MOrderDistributeEntity::getWriterId, 0L).
                eq(MOrderDistributeEntity::getOrderId, orderUnbind.getOrderId()).
                update();

        //订单与写手解除绑定后订单状态变成待开始
        if (CharSequenceUtil.equals(roleKey, "writer")) {
            Optional<SysDictData> first = orderStatusList.stream().filter(item -> item.getDictCode().compareTo(100L) == 0).findFirst();
            String orderStatus = first.isPresent() ? first.get().getDictValue() : "1";
            orders.setOrderStatus(orderStatus);
            ordersMapper.updateOrders(orders);
        }
    }
}
